/**
 * 通用通知模板库
 * 提供预设的通知模板，简化常见场景的通知创建
 */

import React from 'react';
import {
  UploadOutlined,
  DownloadOutlined,
  SyncOutlined,
  DatabaseOutlined,
  ToolOutlined,
  SaveOutlined,
  ImportOutlined,
  ExportOutlined,
  BarChartOutlined,
  MonitorOutlined,
  CloudSyncOutlined,
  FileTextOutlined,
  TableOutlined,
  ApiOutlined,
} from '@ant-design/icons';

import {
  NotificationTemplate,
  NotificationTemplates,
  NotificationType,
  NotificationConfig,
  NotificationTheme,
  AnimationConfig,
} from '../types/notification';

// 默认主题配置
const defaultTheme: NotificationTheme = {
  primaryColor: '#1890ff',
  backgroundColor: 'rgba(0, 0, 0, 0.85)',
  textColor: 'rgba(255, 255, 255, 0.95)',
  borderColor: 'rgba(255, 255, 255, 0.1)',
  shadowColor: 'rgba(0, 0, 0, 0.3)',
  borderRadius: 20,
  fontSize: 13,
  fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
};

// 默认动画配置
const defaultAnimation: AnimationConfig = {
  duration: 400,
  easing: 'cubic-bezier(0.32, 0.72, 0, 1)',
  enableBounce: true,
  enablePulse: true,
  enableBreathing: true,
};

// 默认配置
const defaultConfig: NotificationConfig = {
  persistent: true,
  autoClose: false,
  showProgress: true,
  showTimestamp: true,
  showDuration: false,
  allowDismiss: true,
  displayMode: 'adaptive',
  displayStrategy: 'dynamic-island', // 模板默认显示在Dynamic Island
  maxWidth: 420,
  priority: 0,
  antNotificationDuration: 4,
  transitionDelay: 3000,
};

// 创建模板的辅助函数
const createTemplate = (
  type: NotificationType,
  title: string,
  description?: string,
  config?: Partial<NotificationConfig>,
  theme?: Partial<NotificationTheme>,
  animation?: Partial<AnimationConfig>
): NotificationTemplate => ({
  type,
  title,
  description,
  config: { ...defaultConfig, ...config },
  theme: { ...defaultTheme, ...theme },
  animation: { ...defaultAnimation, ...animation },
});

// 通知模板库
export const notificationTemplates: NotificationTemplates = {
  // 文件上传模板
  fileUpload: createTemplate(
    'upload',
    '文件上传',
    '正在上传文件...',
    {
      showProgress: true,
      showDuration: true,
      priority: 5,
    },
    {
      primaryColor: '#52c41a',
    }
  ),

  // 文件下载模板
  fileDownload: createTemplate(
    'download',
    '文件下载',
    '正在下载文件...',
    {
      showProgress: true,
      showDuration: true,
      priority: 5,
    },
    {
      primaryColor: '#1890ff',
    }
  ),

  // 数据同步模板
  dataSync: createTemplate(
    'sync',
    '数据同步',
    '正在同步数据...',
    {
      showProgress: true,
      showTimestamp: true,
      priority: 7,
    },
    {
      primaryColor: '#722ed1',
    }
  ),

  // 数据处理模板
  dataProcessing: createTemplate(
    'progress',
    '数据处理',
    '正在处理数据...',
    {
      showProgress: true,
      showTimestamp: true,
      showDuration: true,
      priority: 6,
    },
    {
      primaryColor: '#fa8c16',
    }
  ),

  // 系统维护模板
  systemMaintenance: createTemplate(
    'maintenance',
    '系统维护',
    '正在进行系统维护...',
    {
      persistent: true,
      autoClose: false,
      priority: 10,
    },
    {
      primaryColor: '#faad14',
    }
  ),

  // 备份模板
  backup: createTemplate(
    'task',
    '数据备份',
    '正在备份数据...',
    {
      showProgress: true,
      showTimestamp: true,
      priority: 8,
    },
    {
      primaryColor: '#13c2c2',
    }
  ),

  // 导出模板
  export: createTemplate(
    'export',
    '数据导出',
    '正在导出数据...',
    {
      showProgress: true,
      showDuration: true,
      priority: 4,
    },
    {
      primaryColor: '#eb2f96',
    }
  ),

  // 导入模板
  import: createTemplate(
    'import',
    '数据导入',
    '正在导入数据...',
    {
      showProgress: true,
      showDuration: true,
      priority: 4,
    },
    {
      primaryColor: '#52c41a',
    }
  ),

  // 分析模板
  analysis: createTemplate(
    'progress',
    '数据分析',
    '正在分析数据...',
    {
      showProgress: true,
      showTimestamp: true,
      showDuration: true,
      priority: 6,
    },
    {
      primaryColor: '#1890ff',
    }
  ),

  // 监控模板
  monitoring: createTemplate(
    'monitoring',
    '系统监控',
    '正在监控系统状态...',
    {
      persistent: true,
      autoClose: false,
      showTimestamp: true,
      priority: 9,
    },
    {
      primaryColor: '#f5222d',
    }
  ),
};

// 通用通知工具函数
export class NotificationUtils {
  // 创建文件上传通知
  static createFileUploadNotification(fileName: string, fileSize?: number) {
    const template = notificationTemplates.fileUpload;
    return {
      ...template,
      title: '文件上传',
      description: `正在上传 ${fileName}${fileSize ? ` (${this.formatFileSize(fileSize)})` : ''}...`,
      icon: React.createElement(UploadOutlined),
      metadata: {
        fileName,
        fileSize,
        type: 'file-upload',
      },
    };
  }

  // 创建文件下载通知
  static createFileDownloadNotification(fileName: string, fileSize?: number) {
    const template = notificationTemplates.fileDownload;
    return {
      ...template,
      title: '文件下载',
      description: `正在下载 ${fileName}${fileSize ? ` (${this.formatFileSize(fileSize)})` : ''}...`,
      icon: React.createElement(DownloadOutlined),
      metadata: {
        fileName,
        fileSize,
        type: 'file-download',
      },
    };
  }

  // 创建数据同步通知
  static createDataSyncNotification(source: string, target: string) {
    const template = notificationTemplates.dataSync;
    return {
      ...template,
      title: '数据同步',
      description: `正在从 ${source} 同步到 ${target}...`,
      icon: React.createElement(SyncOutlined),
      metadata: {
        source,
        target,
        type: 'data-sync',
      },
    };
  }

  // 创建数据处理通知
  static createDataProcessingNotification(dataType: string, operation: string) {
    const template = notificationTemplates.dataProcessing;
    return {
      ...template,
      title: `${operation}`,
      description: `正在${operation} ${dataType}...`,
      icon: React.createElement(DatabaseOutlined),
      metadata: {
        dataType,
        operation,
        type: 'data-processing',
      },
    };
  }

  // 创建系统维护通知
  static createMaintenanceNotification(maintenanceType: string, estimatedDuration?: number) {
    const template = notificationTemplates.systemMaintenance;
    const durationText = estimatedDuration ? ` (预计 ${estimatedDuration} 分钟)` : '';
    return {
      ...template,
      title: '系统维护',
      description: `正在进行${maintenanceType}${durationText}...`,
      icon: React.createElement(ToolOutlined),
      metadata: {
        maintenanceType,
        estimatedDuration,
        type: 'maintenance',
      },
    };
  }

  // 创建备份通知
  static createBackupNotification(backupType: string, targetLocation: string) {
    const template = notificationTemplates.backup;
    return {
      ...template,
      title: '数据备份',
      description: `正在备份${backupType}到 ${targetLocation}...`,
      icon: React.createElement(SaveOutlined),
      metadata: {
        backupType,
        targetLocation,
        type: 'backup',
      },
    };
  }

  // 创建导出通知
  static createExportNotification(dataType: string, format: string) {
    const template = notificationTemplates.export;
    return {
      ...template,
      title: '数据导出',
      description: `正在导出${dataType}为 ${format} 格式...`,
      icon: React.createElement(ExportOutlined),
      metadata: {
        dataType,
        format,
        type: 'export',
      },
    };
  }

  // 创建导入通知
  static createImportNotification(dataType: string, source: string) {
    const template = notificationTemplates.import;
    return {
      ...template,
      title: '数据导入',
      description: `正在从 ${source} 导入${dataType}...`,
      icon: React.createElement(ImportOutlined),
      metadata: {
        dataType,
        source,
        type: 'import',
      },
    };
  }

  // 创建分析通知
  static createAnalysisNotification(analysisType: string, dataSource: string) {
    const template = notificationTemplates.analysis;
    return {
      ...template,
      title: `${analysisType}`,
      description: `正在分析 ${dataSource}...`,
      icon: React.createElement(BarChartOutlined),
      metadata: {
        analysisType,
        dataSource,
        type: 'analysis',
      },
    };
  }

  // 创建监控通知
  static createMonitoringNotification(monitorTarget: string, metrics: string[]) {
    const template = notificationTemplates.monitoring;
    return {
      ...template,
      title: '系统监控',
      description: `正在监控 ${monitorTarget} (${metrics.join(', ')})...`,
      icon: React.createElement(MonitorOutlined),
      metadata: {
        monitorTarget,
        metrics,
        type: 'monitoring',
      },
    };
  }

  // 格式化文件大小
  static formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  // 格式化持续时间
  static formatDuration(seconds: number): string {
    if (seconds < 60) {
      return `${Math.round(seconds)}秒`;
    } else if (seconds < 3600) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = Math.round(seconds % 60);
      return remainingSeconds > 0 ? `${minutes}分${remainingSeconds}秒` : `${minutes}分`;
    } else {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      return minutes > 0 ? `${hours}小时${minutes}分` : `${hours}小时`;
    }
  }

  // 格式化速度
  static formatSpeed(itemsPerSecond: number, unit: string = '个'): string {
    if (itemsPerSecond < 1) {
      return `${(itemsPerSecond * 60).toFixed(1)}${unit}/分`;
    } else if (itemsPerSecond < 60) {
      return `${itemsPerSecond.toFixed(1)}${unit}/秒`;
    } else {
      return `${(itemsPerSecond / 60).toFixed(1)}${unit}/分`;
    }
  }

  // 计算预计剩余时间
  static calculateEstimatedTime(
    currentProgress: number,
    totalProgress: number,
    elapsedTime: number
  ): number {
    if (currentProgress <= 0) return 0;
    const progressRatio = currentProgress / totalProgress;
    const totalEstimatedTime = elapsedTime / progressRatio;
    return Math.max(0, totalEstimatedTime - elapsedTime);
  }
}
